import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../../core/domain/page.entity';
import {StatusEnum} from '../../../../core/enum/status.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {PaginationUtils} from '../../../../utils/paginationUtils';
import {OtherUtil} from '../../../../utils/other.util';
import { StudentEvaluteformService } from './student-evaluteform.service';
import { FilterEnum, FilterTypeEnum } from '../../../../core/enum/filter.enum';
import { RemoveTag } from '../../../../utils/removeTag';

declare var $: any;

@Component({
  selector: 'app-student-evaluteform',
  templateUrl: './student-evaluteform.component.html',
  styleUrls: ['./student-evaluteform.component.scss'],
  providers: [StudentEvaluteformService]
})
/**********学生评价*************/
export class StudentEvaluteformComponent implements OnInit {
  formname = null;
  pageInfo: PageEntity = new PageEntity();
  allList = [];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = false;

  // 新增
  paperInfos: PaperInfos = new PaperInfos();
  isHoverShow = false;
  // 试题分类树
  treeNodes = [];

  serchSubjectInfos: SerchSubjectInfos = new SerchSubjectInfos();
  pageSubjectList: any[] = [];
  pageSubjectInfo: PageEntity = new PageEntity();
  isVisiblePaper = false;
  mapOfSubjectCheckedId: { [key: string]: boolean } = {};
  isSubjectAllCheck = false;
  isSubjectIndeterminate = false;
  displaySubjectList = [];
  canSureSub = true;

  mainStatus = 1; // 1.显示主页面，2.显示新增页面,3:发布评价

  previewObj = null; // 预览
  previewList = [];
  previewTitle = null;
  letter = [
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J'
  ];

  constructor(
    private service: StudentEvaluteformService,
    private message: NzMessageService,
  ) {
  }

  ngOnInit() {
    this.page(this.pageInfo);
  }

  /*****分页查询*********/
  page(page: PageEntity): void {
    page.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.service.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }


  /*******第几页*******/
  searchPageIndex(event: any) {
    this.pageInfo.first = event;
    this.page(this.pageInfo);
  }

  /*******每页几条*****/
  searchPageSize(event: any) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /**
   * 全选
   * @param value： value
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /**
   * 主页根据id删除逻辑
   */
  delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }

  moveCloseFn(): void {
    this.mapOfCheckedId = {};
    this.canDelete = true;
    this.isAllCheck = false;
  }

  /******删除所选********/
  deleteAll() {
    const arr = this.delByIdsLogic();
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据！');
      return;
    }
    this.service.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.pageInfo.first = 1;
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }


  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOne(ids: string) {
    this.service.delete(ids).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /*******点击查询*********/
  clickSearch() {
    this.pageInfo.first = 1;
    this.formname ? this.pageInfo.filters['name'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: this.formname,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['name'.toString()];
    this.page(this.pageInfo);
  }

  /********点击重置**************/
  resetSearch() {
    this.formname = null;
    this.pageInfo.first = 1;
    delete this.pageInfo.filters['name'.toString()];
    this.page(this.pageInfo);
  }

  /******点击新增业务逻辑处理部分,初始化数据显示部分*********/
  clickAdd() {
    this.mainStatus = 2;
    this.paperInfos = new PaperInfos();
    this.getQusOption();
  }

  /**
   * 创建题
   * @param num:单选，简答
   */
  addItem(num) {
    const dataObj = new CateObj();
    this.serchSubjectInfos.type = num;
    dataObj.cate = num;
    dataObj.extractType = 2;
    if (!this.paperInfos.cateList || this.paperInfos.cateList.length === 0) {
      this.paperInfos.cateList = [];
    }
    this.paperInfos.cateList.push(dataObj);
  }


  /**
   * 点击编辑
   */
  edit(data) {
    this.paperInfos = new PaperInfos();
    this.getQusOption();
    this.service.view(data.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.paperInfos = res.datas;
        if (this.paperInfos.cateList && this.paperInfos.cateList.length > 0) {
          this.paperInfos.cateList.forEach(item => {
            item.sumscore = 0; // 单个题型的分数
            item.sortList = [];
            if (item.randomList && item.randomList.length > 0) {
              const arry = [];
              item.randomList.forEach(subitem => {
                arry.push(subitem.classifyId);
                if (subitem.selectCount && subitem.score) {
                  item.sumscore += subitem.selectCount * subitem.score;
                }
              });
              item.sortList = arry;
            }

            if (item.selectList && item.selectList.length > 0) {
              item.selectList.forEach(temp => {
                if (temp.score) {
                  item.sumscore += temp.score;
                }
                temp['content'.toString()] = temp.questionName;
              });
            }
          });
        }
        this.mainStatus = 2;
      }
    });
  }

  // 新增编辑返回
  back() {
    this.mainStatus = 1;
    this.paperInfos = new PaperInfos();
  }

  /**
   * 下载
   */
  downLoad(rid) {
    this.service.buildExam({id: rid}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.previewObj = res.datas;
        this.previewTitle = null;
        let title = '';
        const list = [];
        if (this.previewObj.cateList && this.previewObj.cateList.length > 0) {
          this.previewObj.cateList.forEach(item => {
            title = title + item.cate + '(共' + item.questionCount + '道)' + ' ';
            if (item.questionList && item.questionList.length > 0) {
              item.questionList.forEach(qust => {
                qust['type'.toString()] = item.cate;
                list.push(qust);
              });
            }
          });
        }
        this.previewTitle = title + '，共计' + this.previewObj.score + '分';
        this.previewList = list;
        setTimeout(() => {
          this.downfile();
        }, 1000);
      }
    });
  }

  downfile() {
    const printContent = document.getElementById('report');
    // const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
    const WindowPrt = window.open('', '', 'left=0,top=0,toolbar=0,scrollbars=0,status=0');
    WindowPrt.document.write(printContent.innerHTML);
    WindowPrt.document.close();
    WindowPrt.focus();
    WindowPrt.print();
    WindowPrt.close();
  }


  /**
   * 转换大写数字
   * @param num:下标
   */
  reCapitalization(num) {
    return OtherUtil.numberToUpperCase(num);
  }

  /**
   * 随机抽题
   * @param num:i
   */
  chooseAuto(num) {
    this.paperInfos.cateList.forEach((item, index) => {
      if (num === index) {
        item.extractType = 2;
      }
    });
  }

  /**
   * 获取分类-试题
   * @param type:123
   */
  getQusOption() {
    this.service.getQuesTree().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.treeNodes = res.datas;
      }
    });
  }

  /**
   * 试题分类选择
   */
  onChangeQuestions(event, type, num) {
    if (event && event.length > 0) {
      this.getQuesRandom(event, type, num);
    }
    this.paperInfos.cateList.forEach((item, index) => {
      if (num === index) {
        item.selectList = [];
      }
    });
    this.calculation();
  }

  /**
   * 获取分类下试题-随机
   */
  getQuesRandom(event, types, num) {
    const request = {
      type: types,
      classifyIdList: event
    };
    this.service.getCountItem(request).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.paperInfos.cateList.forEach((item, index) => {
          if (num === index) {
            item.randomList = res.datas;
          }
        });
      }
    });
  }

  /**
   * 点击选中试题modal
   * @param qCate num:i
   */
  chooseModal(qCate, num) {
    delete this.pageSubjectInfo.filters['id'.toString()];
    delete this.pageSubjectInfo.filters['content'.toString()];
    this.paperInfos.cateList.forEach((item, index) => {
      if (num === index) {
        item.extractType = 1;
      }
    });
    // index
    this.serchSubjectInfos.type = num;
    this.isVisiblePaper = true;
    if (this.treeNodes && this.treeNodes.length > 0) {
      this.pageSubjectInfo.filters['classifyId'.toString()] = PaginationUtils.filters(this.treeNodes[0].key, (FilterEnum.EQUALS).toString());
    }
    this.pageSubjectInfo.filters['type'.toString()] = PaginationUtils.filters(qCate, (FilterEnum.EQUALS).toString());
    this.serchSubjectInfos.subjectContent = null;
    this.getSubjectPage(this.pageSubjectInfo);
  }

  /**
   * 试题树点击-modal
   * @param event value
   */
  subjectClick(event) {
    delete this.pageSubjectInfo.filters['content'.toString()];
    this.serchSubjectInfos.subjectContent = null;
    this.pageSubjectInfo.filters['classifyId'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: event.node.key
    };
    this.getSubjectPage(this.pageSubjectInfo);
  }

  /**
   * 点击查询-试题
   */
  setSubjectPage(): void {
    this.pageSubjectInfo.first = 1;
    if (this.serchSubjectInfos.subjectContent) {
      this.pageSubjectInfo.filters['content'.toString()] = PaginationUtils.filters(
        this.serchSubjectInfos.subjectContent, (FilterEnum.CONTAINS).toString());
    } else {
      delete this.pageSubjectInfo.filters['content'.toString()];
    }
    this.getSubjectPage(this.pageSubjectInfo);
  }

  /**
   * 点击查询-重置
   */
  resetSubjectSearch() {
    this.serchSubjectInfos.subjectContent = '';
    delete this.pageSubjectInfo.filters['content'.toString()];
    this.getSubjectPage(this.pageSubjectInfo);
  }

  /**
   * 分页获取题目数据
   * @param page 分页条件
   */
  getSubjectPage(page: PageEntity): void {
    this.service.pageSubjectList(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.pageSubjectList = res.datas.data;
        this.pageSubjectList.length > 0 ? this.pageSubjectInfo.totalRecords = res.datas.totalRecords : this.isSubjectAllCheck = false;
      }
    });
  }

  /**
   * 当前页面展示数据改变的回调函数
   */
  currentSbPageDataChange($event): void {
    this.displaySubjectList = $event;
    this.refreshSbStatus();
  }

  /**
   * 全选
   */
  checkSbAll(value: boolean): void {
    this.displaySubjectList.forEach(item => (this.mapOfSubjectCheckedId[item.id] = value));
    this.refreshSbStatus();
  }

  /**
   * 单选
   */
  refreshSbStatus(): void {
    this.isSubjectAllCheck = this.displaySubjectList.every(item => this.mapOfSubjectCheckedId[item.id]);
    this.isSubjectIndeterminate =
      this.displaySubjectList.some(item => this.mapOfSubjectCheckedId[item.id]) &&
      !this.isSubjectAllCheck;
    this.checkSubDelete();
  }

  /**
   * 判断是否选择了数据
   */
  checkSubDelete(): void {
    this.canSureSub = OtherUtil.deleteIds(this.mapOfSubjectCheckedId).length <= 0;
  }

  /**
   * 去掉后台返回数据标签
   * @param str:数据对象
   */
  strTagEleChange(str: string) {
    return RemoveTag.removeTagLogic(str);
  }

  // 去除标签
  setText(html) {
    return html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
      .replace(/<br\/?>/gi, '\n')
      .replace(/<[^>/]+>/g, '')
      .replace(/(\n)?<\/([^>]+)>/g, '')
      .replace(/\u00a0/g, ' ')
      .replace(/&nbsp;/g, ' ')
      .replace(/<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>/g, '')
      .replace(/<\/?(a)[^>]*>/g, '');  // 去除a标签
  }


  /**
   * 确定选择的试题
   */
  submitSubject() {
    const arr = [];
    for (const val in this.mapOfSubjectCheckedId) {
      if (this.mapOfSubjectCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length <= 0) {
      this.message.warning('请先勾选题目!');
      return;
    }
    this.pageSubjectInfo = new PageEntity();
    this.pageSubjectInfo.filters['id'.toString()] = PaginationUtils.filters(
      arr.join(','), (FilterEnum.IN).toString());
    this.service.getSubjectList(this.pageSubjectInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfSubjectCheckedId = {};
        this.pageSubjectInfo.first = 1;
        this.paperInfos.cateList.forEach((item, index) => {
          if (this.serchSubjectInfos.type === index) {
            item.extractType = 1;
            if (!item.selectList) {
              item['selectList'.toString()] = [];
            }
            if (res.datas && res.datas.length > 0) {
              res.datas.forEach(temp => {
                temp['questionId'.toString()] = temp.id;
                item.selectList.push(temp);
              });
            }
          }
        });
        // 去重
        if (this.paperInfos.cateList[this.serchSubjectInfos.type].selectList) {
          this.paperInfos.cateList[this.serchSubjectInfos.type].selectList =
            this.paperInfos.cateList[this.serchSubjectInfos.type].selectList.reduce(
              (x, y) => x.findIndex(e => e.id === y.id) < 0 ? [...x, y] : x, []); // 去重
        }
        this.isVisiblePaper = false;
        // 清除随机抽题
        this.paperInfos.cateList[this.serchSubjectInfos.type].randomList = [];
        this.calculation();
      }
    });
  }

  /**
   * 排序
   * @ param arr
   * @ param index1 index2排序showSort
   * @ param index2
   */
  swapItems(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  /**
   * 删除加的题目
   * @param ic:第一级，num:第二级
   * @param num:i
   */
  deleteItem(ic, num) {
    this.paperInfos.cateList.forEach((item, index) => {
      if (index === ic) {
        item.selectList.splice(num, 1);
      }
    });
    this.calculation();
  }

  /**
   * 排序试题
   * @param ic 第一级，num 第二级
   */
  upDataItem(ic: number, num: number) {
    if (this.paperInfos.cateList[ic].selectList.length > 1 && num !== 0) {
      this.paperInfos.cateList[ic].selectList = this.swapItems(this.paperInfos.cateList[ic].selectList, num, num - 1);
    }
  }

  /**
   * 排序试题
   * @param ic:i
   * @param num:n
   */
  downDataItem(ic: number, num: number) {
    if (this.paperInfos.cateList[ic].selectList.length > 1 && num !== (this.paperInfos.cateList[ic].selectList.length - 1)) {
      this.paperInfos.cateList[ic].selectList = this.swapItems(this.paperInfos.cateList[ic].selectList, num, num + 1);
    }
  }

  /**
   * 分数change
   * @param num:i
   */
  scoChange(num) {
    this.paperInfos.cateList[num].score = null;
    this.calculation();
  }

  /**
   * 计算总分，总题
   */
  calculation() {
    this.paperInfos.questionCount = 0;
    this.paperInfos.score = 0;
    this.paperInfos.cateList.forEach(item => {
      item.questionCount = 0; // 单个题型的数量
      item.sumscore = 0; // 单个题型的分数
      if (item.selectList && item.selectList.length > 0) {
        item.questionCount = item.selectList.length;
        item.selectList.forEach(temp => {
          if (temp.score) {
            item.sumscore += temp.score;
          }
        });
      }
      if (item.randomList && item.randomList.length > 0) {
        item.randomList.forEach(temp => {
          if (temp.selectCount) {
            item.questionCount += temp.selectCount;
          }
          if (temp.selectCount && temp.score) {
            item.sumscore += temp.selectCount * temp.score;
          }
        });
      }
      if (item.questionCount) {
        this.paperInfos.questionCount += item.questionCount;
      }
      if (item.sumscore) {
        this.paperInfos.score += item.sumscore;
      }
    });
  }

  /**
   * 设置每题分
   * @param num:i
   */
  setAverage(num) {
    this.paperInfos.cateList.forEach((item, index) => {
      if (num === index) {
        item.sumscore = 0;
        if (item.randomList && item.randomList.length > 0) {
          item.randomList.forEach(temp => {
            // 设置平均分
            if (item.score) {
              temp.score = item.score;
            }
            // 计算改变后的总分-大题
            if (temp.selectCount && temp.score) {
              item.sumscore += temp.selectCount * temp.score;
            }
          });
        }
        if (item.selectList && item.selectList.length > 0) {
          item.sumscore = 0;
          item.questionCount = item.selectList.length;
          item.selectList.forEach(temp => {
            temp.score = item.score;
          });
        }
      }
      this.calculation();
    });
  }

  /**
   * 删除加的题目类型
   * @param num:index
   */
  deleteItemType(num: number) {
    this.paperInfos.cateList.splice(num, 1);
    this.calculation();
  }

  /**
   * 排序整类
   * @param index 排序showSort
   */
  upData(index: number) {
    if (this.paperInfos.cateList.length > 1 && index !== 0) {
      this.paperInfos.cateList = this.swapItems(this.paperInfos.cateList, index, index - 1);
    }
  }

  /**
   * 排序整类
   * @param index 排序showSort
   */
  downData(index: number) {
    if (this.paperInfos.cateList.length > 1 && index !== (this.paperInfos.cateList.length - 1)) {
      this.paperInfos.cateList = this.swapItems(this.paperInfos.cateList, index, index + 1);
    }
  }

  /**
   * 取消
   */
  cancel() {
    this.mainStatus = 1;
    this.paperInfos = new PaperInfos();
  }

  /**
   * 保存
   */
  save() {
    if (!this.paperInfos.name) {
      this.message.warning('请填写评价表名称！');
      return;
    }
    // if (!this.paperInfos.score) {
    //   this.message.warning('请设置题目分数！');
    //   return;
    // }
    let temps = false;
    for (const item of this.paperInfos.cateList) {
      if (!item.questionCount) {
        temps = true;
        break;
      }
      if (item.questionCount === 0) {
        temps = true;
        break;
      }
      let temps1 = false;
      if (item.cate == '单选题') {
        if (!item.score || item.score == 0) {
          if (item.randomList && item.randomList.length > 0) {
            for (const rand of item.randomList) {
              if (!rand.score || rand.score == 0) {
                temps1 = true;
                break;
              }
            }
          }

          if (item.selectList && item.selectList.length > 0) {
            for (const rand1 of item.selectList) {
              if (!rand1.score || rand1.score == 0) {
                temps1 = true;
                break;
              }
            }
          }
        }
      }
      if (temps1) {
        temps = true;
        break;
      }
    }
    if (temps) {
      this.message.warning('题目或单选题题目分数不能为空！');
      return;
    }
    const opt = this.paperInfos.id ? 'update' : 'create';
    this.service[opt](this.paperInfos).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mainStatus = 1;
        this.page(this.pageInfo);
      }
    });
  }

  // 预览
  preview(data) {
    this.service.buildExam({id: data.id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.previewObj = res.datas;
        this.previewTitle = null;
        this.mainStatus = 3;
        let title = '';
        const list = [];
        if (this.previewObj.cateList && this.previewObj.cateList.length > 0) {
          this.previewObj.cateList.forEach(item => {
            title = title + item.cate + '(共' + item.questionCount + '道)' + ' ';
            if (item.questionList && item.questionList.length > 0) {
              item.questionList.forEach(qust => {
                qust['type'.toString()] = item.cate;
                list.push(qust);
              });
            }
          });
        }
        this.previewTitle = title + '，共计' + this.previewObj.score + '分';
        this.previewList = list;
      }
    });
  }

}

class TopSearchObj {
  value1?: string;
  value2?: string;
  value3?: string;
  value4?: string;
  value5?: string;
}

class AddObj {
  value1?: string;
  value2?: string;
  value3?: string;
  value4?: string;
  value5?: string;
  value6?: string;
}

/**
 * 新增试卷实体
 */
class PaperInfos {
  id?: string;
  name?: string;
  questionCount?: number; // 试卷总题数
  // 试卷卷面总分
  score?: number;
  cateList?: Array<CateObj>; // 大题分类列表
}

class CateObj {
  cate?: string; // 试题类型：单选题、简答题
  extractType?: number; // 抽题方式；1：选择试题；2：随机抽题
  id?: string;
  questionCount?: number; // 分类下总题数
  sortList: any[]; // 选择的分类id
  randomList?: Array<RandomObj>; // 随机选题列表
  score?: number; // 试题分数，每题多少分；为空时可能该题型每道题的给定分数不一样，不为空时该题型每道题分时统一
  sumscore?: number; // 试题共多少分
  selectList?: Array<SelectObj>; // 自选题目列表
  sortIndex?: number; // 位置排序
}

class RandomObj {
  classifyId?: string; // 试题分类id
  id?: string;
  score?: number; // 试题分数
  selectCount?: number; // 该题型下抽取多少道题
  classifyName?: string;
  count?: number; // 总共多少道
}

class SelectObj {
  id?: string;
  content?: string;
  questionId?: string;
  questionName?: string;
  score?: number; // 试题分数
  sortIndex?: number; // 位置排序
  selectList?: any;
}

/**
 * 试提Modal顶部实体
 */
export class SerchSubjectInfos {
  subjectContent?: string;
  type?: number;
}
